<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>第一个ajax程序</title>
<script type="text/javascript">
	function createXmlHttpResquest() {
		//创建ajax引擎
		if (window.XMLHttpRequest) {
			//高版本浏览器
			return new XMLHttpRequest();
		} else {
			//兼容IE5和IE6以及更低版本的浏览器
			return new ActiveXObject("Microsoft.XMLHTTP")
		}
	}
	function validate() {
	
		var username = document.getElementById("username").value;
		//1.创建XmlHttpRequest对象
		var xmlHttpRequest = createXmlHttpResquest();
		//2.通过XmlHttpRequest对象设置请求信息
		//xmlHttpRequest.open("GET","existsuser?checkname="+username,true);
		xmlHttpRequest.open("POST","existsuser", true);
		xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

		//3.向服务器发送请求
		//xmlHttpRequest.send(null);
		xmlHttpRequest.send("checkname="+username );
		
		//4.创建回调函数
		xmlHttpRequest.onreadystatechange = callback;
		//根据响应状态动态更新页面
		function callback() {
			//就绪状态是4且状态码是200,表示正确完成
			if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
				//动态修改DOM元素或元素样式
				var msg = document.getElementById("msg");
				msg.innerHTML = "";
				if (xmlHttpRequest.responseText == "1") {
					msg.style.display = "block";
					msg.innerHTML = "用户名被占用，不能被注册"
				} else if (xmlHttpRequest.responseText == "0") {
					msg.style.display = "block";
					msg.innerHTML = "用户名可以使用";
				} else {
					msg.style.display = "none";
					msg.innerHTML = "";
				}
			}
		}
	}
</script>
</head>
<body>
	<form action="" method="post">
		<p>
			用户名：<input type="text" id="username" name="username"
				onblur="validate()" />
		</p>
		<p id="msg" style="display:none;"></p>

		<input type="submit" value="注册" />
	</form>

</body>
</html>